package com.ruoyi.module.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.module.domain.UserWordRecord;
import com.ruoyi.module.domain.UserChapterRecord;
import com.ruoyi.module.domain.UserReviewRecord;
import com.ruoyi.module.service.IUserWordRecordService;
import com.ruoyi.module.service.IUserChapterRecordService;
import com.ruoyi.module.service.IUserReviewRecordService;

/**
 * 学习记录Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/learning")
public class LearningController extends BaseController
{
    @Autowired
    private IUserWordRecordService userWordRecordService;

    @Autowired
    private IUserChapterRecordService userChapterRecordService;

    @Autowired
    private IUserReviewRecordService userReviewRecordService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 保存单词记录
     */
    @Log(title = "保存单词记录", businessType = BusinessType.INSERT)
    @PostMapping("/word-record")
    public AjaxResult saveWordRecord(@RequestBody Map<String, Object> params)
    {
        try {
            UserWordRecord record = new UserWordRecord();
            record.setUserId(SecurityUtils.getUserId());
            record.setWord((String) params.get("word"));
            record.setDictId((String) params.get("dictId"));
            
            if (params.get("chapter") != null) {
                record.setChapter((Integer) params.get("chapter"));
            }
            
            record.setTimestamp(System.currentTimeMillis());
            record.setWrongCount((Integer) params.get("wrongCount"));
            
            // 将timing数组转为JSON字符串
            record.setTiming(objectMapper.writeValueAsString(params.get("timing")));
            
            // 将mistakes对象转为JSON字符串
            if (params.get("mistakes") != null) {
                record.setMistakes(objectMapper.writeValueAsString(params.get("mistakes")));
            }
            
            // 计算总时间
            List<Integer> timingArray = (List<Integer>) params.get("timing");
            int totalTime = 0;
            if (timingArray != null) {
                for (Integer time : timingArray) {
                    totalTime += time;
                }
            }
            record.setTotalTime(totalTime);
            
            int result = userWordRecordService.insertUserWordRecord(record);
            if (result > 0) {
                return AjaxResult.success().put("id", record.getId());
            }
            return AjaxResult.error("保存失败");
        } catch (Exception e) {
            logger.error("保存单词记录失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 批量保存单词记录
     */
    @Log(title = "批量保存单词记录", businessType = BusinessType.INSERT)
    @PostMapping("/word-record/batch")
    public AjaxResult batchSaveWordRecords(@RequestBody Map<String, Object> params)
    {
        try {
            List<Map<String, Object>> recordsList = (List<Map<String, Object>>) params.get("records");
            List<UserWordRecord> records = new ArrayList<>();
            Long userId = SecurityUtils.getUserId();
            
            for (Map<String, Object> node : recordsList) {
                UserWordRecord record = new UserWordRecord();
                record.setUserId(userId);
                record.setWord((String) node.get("word"));
                record.setDictId((String) node.get("dictId"));
                
                if (node.get("chapter") != null) {
                    record.setChapter((Integer) node.get("chapter"));
                }
                
                record.setTimestamp(System.currentTimeMillis());
                record.setWrongCount((Integer) node.get("wrongCount"));
                record.setTiming(objectMapper.writeValueAsString(node.get("timing")));
                
                if (node.get("mistakes") != null) {
                    record.setMistakes(objectMapper.writeValueAsString(node.get("mistakes")));
                }
                
                records.add(record);
            }
            
            int result = userWordRecordService.batchInsertUserWordRecord(records);
            return AjaxResult.success("成功保存 " + result + " 条记录");
        } catch (Exception e) {
            logger.error("批量保存单词记录失败", e);
            return AjaxResult.error("批量保存失败: " + e.getMessage());
        }
    }

    /**
     * 查询单词记录列表
     */
    @GetMapping("/word-record/list")
    public TableDataInfo listWordRecords(UserWordRecord userWordRecord)
    {
        startPage();
        userWordRecord.setUserId(SecurityUtils.getUserId());
        List<UserWordRecord> list = userWordRecordService.selectUserWordRecordList(userWordRecord);
        return getDataTable(list);
    }

    /**
     * 查询错词记录
     */
    @GetMapping("/word-record/errors")
    public AjaxResult getErrorWords(UserWordRecord userWordRecord)
    {
        try {
            userWordRecord.setUserId(SecurityUtils.getUserId());
            List<UserWordRecord> list = userWordRecordService.selectErrorWordRecords(userWordRecord);
            
            // 按单词分组
            Map<String, Map<String, Object>> groupMap = new HashMap<>();
            
            for (UserWordRecord record : list) {
                String key = record.getWord() + "_" + record.getDictId();
                if (!groupMap.containsKey(key)) {
                    Map<String, Object> group = new HashMap<>();
                    group.put("word", record.getWord());
                    group.put("dict", record.getDictId());
                    group.put("wrongCount", record.getWrongCount());
                    group.put("records", new ArrayList<>());
                    groupMap.put(key, group);
                }
                ((List<UserWordRecord>) groupMap.get(key).get("records")).add(record);
            }
            
            List<Map<String, Object>> rows = new ArrayList<>(groupMap.values());
            
            AjaxResult result = AjaxResult.success();
            result.put("rows", rows);
            result.put("total", rows.size());
            return result;
        } catch (Exception e) {
            logger.error("查询错词记录失败", e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 保存章节记录
     */
    @Log(title = "保存章节记录", businessType = BusinessType.INSERT)
    @PostMapping("/chapter-record")
    public AjaxResult saveChapterRecord(@RequestBody Map<String, Object> params)
    {
        try {
            UserChapterRecord record = new UserChapterRecord();
            record.setUserId(SecurityUtils.getUserId());
            record.setDictId((String) params.get("dictId"));
            
            if (params.get("chapter") != null) {
                record.setChapter((Integer) params.get("chapter"));
            }
            
            record.setTimestamp(System.currentTimeMillis());
            record.setTime((Integer) params.get("time"));
            record.setCorrectCount((Integer) params.get("correctCount"));
            record.setWrongCount((Integer) params.get("wrongCount"));
            record.setWordCount((Integer) params.get("wordCount"));
            record.setWordNumber((Integer) params.get("wordNumber"));
            
            // 将数组转为JSON字符串
            if (params.get("correctWordIndexes") != null) {
                record.setCorrectWordIndexes(objectMapper.writeValueAsString(params.get("correctWordIndexes")));
            }
            if (params.get("wordRecordIds") != null) {
                record.setWordRecordIds(objectMapper.writeValueAsString(params.get("wordRecordIds")));
            }
            
            // 计算统计数据
            int wordCount = record.getWordCount();
            int time = record.getTime();
            int correctCount = record.getCorrectCount();
            int wrongCount = record.getWrongCount();
            
            // WPM = (单词数 / 时间) * 60
            if (time > 0) {
                record.setWpm((int)Math.round((double)wordCount / time * 60));
            }
            
            // 按键正确率 = 正确按键数 / (正确按键数 + 错误按键数) * 100
            if (correctCount + wrongCount > 0) {
                record.setInputAccuracy((int)Math.round((double)correctCount / (correctCount + wrongCount) * 100));
            }
            
            // 单词正确率
            List<Integer> correctIndexes = (List<Integer>) params.get("correctWordIndexes");
            int correctWords = correctIndexes != null ? correctIndexes.size() : 0;
            int totalWords = record.getWordNumber();
            if (totalWords > 0) {
                record.setWordAccuracy((int)Math.round((double)correctWords / totalWords * 100));
            }
            
            int result = userChapterRecordService.insertUserChapterRecord(record);
            if (result > 0) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("id", record.getId());
                ajax.put("wpm", record.getWpm());
                ajax.put("inputAccuracy", record.getInputAccuracy());
                ajax.put("wordAccuracy", record.getWordAccuracy());
                return ajax;
            }
            return AjaxResult.error("保存失败");
        } catch (Exception e) {
            logger.error("保存章节记录失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 查询章节记录列表
     */
    @GetMapping("/chapter-record/list")
    public TableDataInfo listChapterRecords(UserChapterRecord userChapterRecord)
    {
        startPage();
        userChapterRecord.setUserId(SecurityUtils.getUserId());
        List<UserChapterRecord> list = userChapterRecordService.selectUserChapterRecordList(userChapterRecord);
        return getDataTable(list);
    }

    /**
     * 获取章节进度
     */
    @GetMapping("/chapter-record/progress/{dictId}")
    public AjaxResult getChapterProgress(@PathVariable String dictId)
    {
        UserChapterRecord query = new UserChapterRecord();
        query.setUserId(SecurityUtils.getUserId());
        query.setDictId(dictId);
        
        List<UserChapterRecord> list = userChapterRecordService.selectUserChapterRecordList(query);
        
        // 统计完成的章节
        List<Integer> completedChapters = new ArrayList<>();
        for (UserChapterRecord record : list) {
            if (record.getChapter() != null && record.getChapter() >= 0) {
                if (!completedChapters.contains(record.getChapter())) {
                    completedChapters.add(record.getChapter());
                }
            }
        }
        
        // 获取最后章节
        int lastChapter = 0;
        for (Integer chapter : completedChapters) {
            if (chapter > lastChapter) {
                lastChapter = chapter;
            }
        }
        
        AjaxResult ajax = AjaxResult.success();
        ajax.put("dictId", dictId);
        ajax.put("completedChapters", completedChapters);
        ajax.put("totalChapters", lastChapter + 1);
        ajax.put("lastChapter", lastChapter);
        ajax.put("completionRate", completedChapters.size());
        
        return ajax;
    }

    /**
     * 创建复习任务
     */
    @Log(title = "创建复习任务", businessType = BusinessType.INSERT)
    @PostMapping("/review-record")
    public AjaxResult createReviewRecord(@RequestBody Map<String, Object> params)
    {
        try {
            UserReviewRecord record = new UserReviewRecord();
            record.setUserId(SecurityUtils.getUserId());
            record.setDictId((String) params.get("dictId"));
            record.setIndex(0);
            record.setCreateTimestamp(System.currentTimeMillis());
            record.setIsFinished(0);
            
            // 将单词数组转为JSON字符串
            if (params.get("words") != null) {
                record.setWords(objectMapper.writeValueAsString(params.get("words")));
            }
            
            int result = userReviewRecordService.insertUserReviewRecord(record);
            if (result > 0) {
                return AjaxResult.success().put("id", record.getId());
            }
            return AjaxResult.error("创建失败");
        } catch (Exception e) {
            logger.error("创建复习任务失败", e);
            return AjaxResult.error("创建失败: " + e.getMessage());
        }
    }

    /**
     * 更新复习进度
     */
    @Log(title = "更新复习进度", businessType = BusinessType.UPDATE)
    @PutMapping("/review-record/{id}")
    public AjaxResult updateReviewRecord(@PathVariable Long id, @RequestBody Map<String, Object> params)
    {
        try {
            UserReviewRecord record = userReviewRecordService.selectUserReviewRecordById(id);
            if (record == null) {
                return AjaxResult.error("记录不存在");
            }
            
            if (params.get("index") != null) {
                record.setIndex((Integer) params.get("index"));
            }
            if (params.get("isFinished") != null) {
                record.setIsFinished((Integer) params.get("isFinished"));
            }
            if (params.get("words") != null) {
                record.setWords(objectMapper.writeValueAsString(params.get("words")));
            }
            
            int result = userReviewRecordService.updateUserReviewRecord(record);
            return toAjax(result);
        } catch (Exception e) {
            logger.error("更新复习进度失败", e);
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取复习记录列表
     */
    @GetMapping("/review-record/list")
    public TableDataInfo listReviewRecords(UserReviewRecord userReviewRecord)
    {
        startPage();
        userReviewRecord.setUserId(SecurityUtils.getUserId());
        List<UserReviewRecord> list = userReviewRecordService.selectUserReviewRecordList(userReviewRecord);
        return getDataTable(list);
    }

    /**
     * 删除复习记录
     */
    @Log(title = "删除复习记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/review-record/{id}")
    public AjaxResult deleteReviewRecord(@PathVariable Long id)
    {
        return toAjax(userReviewRecordService.deleteUserReviewRecordById(id));
    }
}

